package com.trade.system.security;

import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Class Description:系统访问资源控制，根据具登录用户角色的不同判断用户可访问的资源权限
 *              (过滤器)
 * @Version v1.0 2017/4/22 3:32
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Log4j
@Component
@Order(value = 1) //控制配置类的加载顺序,越小越先加載
public class FilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource,InitializingBean{

    @Autowired
    private UrlCache urlCache;

    private static HashMap<String,List<String>> urlRoles;

    /**
     * 获取属性
     *
     * @param object 获取请求的对象
     * @return Collection<ConfigAttribute> 配置属性集合
     * @throws IllegalArgumentException 非法参数异常
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi=(FilterInvocation)object;
        HttpServletRequest request = fi.getRequest();
        String servletPath = request.getServletPath();
        String method = request.getMethod();
        String url=fi.getRequestUrl();
        Set<String> urlSet = urlRoles.keySet();
        SecurityUtil.getRegexUrl(servletPath+"@"+method,urlSet);
        List<String> roles_=urlRoles.get(url);
        log.info("Url Associated Roles :" + roles_);
        if(roles_==null){
            return SecurityConfig.createList(new String[0]);
        }
        String[] stockArr = new String[roles_.size()];
        stockArr = roles_.toArray(stockArr);
        return SecurityConfig.createList(stockArr);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //加载角色资源Map
        urlCache.loadUrlRoles();
        //获取资源角色map
        urlRoles = urlCache.getUrlRoles();
        //添加定时任务信息
    }
}
